package aom.ju.ss.view.dicker

import androidx.core.content.ContextCompat
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentPagerAdapter
import aom.ju.ss.R
import aom.ju.ss.databinding.DickerFragmentBinding
import aom.ju.ss.mode.AllClass
import aom.ju.ss.mode.BannerMode
import aom.ju.ss.utils.*
import aom.ju.ss.utils.http.LP_API.get_banner_list
import aom.ju.ss.utils.http.LP_API.get_tree
import aom.ju.ss.utils.http.LP_API.user_banner_activity_list
import aom.ju.ss.utils.http.LP_API.user_barter_activity_list
import aom.ju.ss.utils.http.OKHttpUtils
import aom.ju.ss.view.base.BaseFragment
import com.google.android.material.appbar.AppBarLayout.OnOffsetChangedListener
import com.google.android.material.tabs.TabLayout
import com.google.gson.Gson
import kotlin.concurrent.thread


/**
 * 首页 易货
 */
class DickerFragment : BaseFragment() {

    companion object {
        fun getMys(): DickerFragment {
            return DickerFragment()
        }
    }

    private lateinit var binding: DickerFragmentBinding
    private var banners = arrayListOf<banner140Item>()

    private var cxFragments = arrayListOf<banner140Item>()


    override fun init() {
        binding = viewBinding as DickerFragmentBinding
        val dra = ContextCompat.getDrawable(activity, R.drawable.ic_sanjiao_xia)
        dra?.setBounds(0, 0, dra.minimumWidth, dra.intrinsicHeight);
        binding.titleView7.title.setCompoundDrawables(null, null, dra, null)
        binding.titleView7.title.compoundDrawablePadding = 4.dp
        binding.titleView7.backImg.setPadding(9.dp, 9.dp, 9.dp, 9.dp)

        initBanner()
        initcx()//促销
        initGoods()

        binding.titleView7.title.setOnClickListener { }
        binding.titleView7.r_img.setOnClickListener { }
        binding.titleView7.r_img_two.setOnClickListener { }
        binding.titleView7.backImg.setOnClickListener { }

        binding.sr.setOnRefreshListener {
            httpData()

            val fs = fs[binding.vp1.currentItem]
            fs?.binding?.small?.autoRefresh()
            thread {
                Thread.sleep(2000)
                activity.runOnUiThread {
                    binding.sr.isRefreshing = false
                }
            }

        }

        binding.appbar.addOnOffsetChangedListener(OnOffsetChangedListener { _, verticalOffset ->
            binding.sr.isEnabled = verticalOffset >= 0
        })//布局嵌套 滚动冲突问题

        httpData()
    }

    private fun httpData() {

        OKHttpUtils(activity, false)
            .SetApiUrl(get_banner_list)
            .SetKey("seat_id")
            .SetValue("1")
            .POST(this)

        OKHttpUtils(activity, false)
            .SetApiUrl(user_banner_activity_list)
            .SetKey("city", "lat", "lng")
            .SetValue(
                SpUtils.getString("city", "长沙市"),
                SpUtils.getString("lat", "28.17657269042584"),
                SpUtils.getString("lng", "112.9750590951538")
            )
            .POST(this)

        if (SpUtils.getString("allclass").length > 1) {
            initClassView(SpUtils.getString("allclass"))
        } else {
            OKHttpUtils(activity, false)
                .SetApiUrl(get_tree)
                .POST(this)
        }
    }

    override fun ok(jsonString: String?, httpTY: String?) {
        super.ok(jsonString, httpTY)
        when (httpTY) {
            get_tree -> {
                initClassView(jsonString)
            }
            get_banner_list -> {
                banners.clear()//banner fragment 数据

                val mode = Gson().fromJson(jsonString, BannerMode::class.java)
                mode.data?.let {
                    for (a in it) {
                        banners.add(banner140Item.getMys(a.image))
                    }
                    binding.vp.adapter?.notifyDataSetChanged()
                }
            }
            user_banner_activity_list -> {
                cxFragments.clear()//促销数据
                binding.cxVp.adapter?.notifyDataSetChanged()
//                val mode=Gson().fromJson(jsonString,)
            }
        }
    }

    private fun initClassView(jsonString: String?) {

        val mode = Gson().fromJson(jsonString, AllClass::class.java)
        SpUtils.putString(
            "allclass", jsonString, (1000 * 60 * 60 * 24)// 一天后过期
        )

        for ((a, i) in fs.withIndex()) {
            fs[a] = null
        }

        fs.clear()//商品数据
        ts.clear()//商品tab


        fs.add(BarterGoods.getMys("", SpUtils.getString("city", "长沙市")))
        ts.add("全部")
        for (a in mode.data) {
            fs.add(BarterGoods.getMys(a.id.toString(), SpUtils.getString("city", "长沙市")))
            ts.add(a.title)
            binding.vp1.adapter?.notifyDataSetChanged()
        }
    }

    override fun error(e: String?, jsonString: String?, httpTY: String?) {
        super.error(e, jsonString, httpTY)
        e?.show
    }


    val fs = arrayListOf<BarterGoods?>()
    val ts = arrayListOf<String>()

    private fun initGoods() {

        binding.vp1.adapter = object : FragmentPagerAdapter(childFragmentManager, 1) {
            override fun getCount(): Int {
                return fs.size
            }

            override fun getItem(position: Int): Fragment {
                return if (fs[position] == null) Fragment() else fs[position]!!
            }

            override fun getPageTitle(position: Int): CharSequence {
                return ts[position]
            }
        }
        binding.tab.setupWithViewPager(binding.vp1)

        binding.tab.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener {
            override fun onTabSelected(tab: TabLayout.Tab?) {


            }

            override fun onTabUnselected(tab: TabLayout.Tab?) {
            }

            override fun onTabReselected(tab: TabLayout.Tab?) {
                for ((a, i) in ts.withIndex()) {
                    if (i == tab?.text) {
                        fs[a]?.let {
                            it.binding?.small?.autoRefresh()
                        }
                    }
                }
            }

        })


    }

    private fun initcx() {

        cxFragments.add(
            banner140Item.getMys(
                "http://p9.itc.cn/images03/20200524/4eb8e1c7e114462695df6e7637325d53.jpeg",
                "",
                ""
            )
        )
        cxFragments.add(
            banner140Item.getMys(
                "http://p6.itc.cn/images03/20200524/272e69c926344ea0b524ed7ae6f58192.jpeg",
                "",
                ""
            )
        )
        cxFragments.add(
            banner140Item.getMys(
                "http://qqpublic.qpic.cn/qq_public/0/0-2689488684-34D25407EBA48B0A0A520B806C3B8173/0?fmt=jpg&size=156&h=1310&w=900&ppv=1/0",
                ",",
                ""
            )
        )

        binding.cxVp.adapter = object : FragmentPagerAdapter(childFragmentManager, 1) {
            override fun getCount(): Int {
                return cxFragments.size

            }

            override fun getItem(position: Int): Fragment {
                return cxFragments[position]
            }

        }
        binding.cxVp.jop(3000)

        binding.cjLay.setOnClickListener { }//抽奖
        binding.hbLay.setOnClickListener { }//红包
        binding.moreCx.setOnClickListener { }//促销活动

    }

    private fun initBanner() {


        binding.vp.adapter = object : FragmentPagerAdapter(childFragmentManager, 1) {
            override fun getCount(): Int {
                return banners.size

            }

            override fun getItem(position: Int): Fragment {
                return banners[position]
            }

        }
        binding.vp.pageMargin = 30
        binding.vp.currentItem = 0
        binding.vp.jop(3000)
        binding.myInd.setViewPager(binding.vp)

    }

    override fun getLay(): Int {
        return R.layout.dicker_fragment
    }
}